<?php

declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\LogisticsRules as LogisticsRulesModel;
use app\admin\common\ServiceResponse;
use app\common\Calculate;
use think\facade\Db;
use app\admin\model\Product as ProductModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use app\common\ExchangeRateHostAPI;

class LogisticsRules extends BaseService
{

    use ServiceResponse;

    protected $model;
    public function __construct()
    {
        parent::__construct();
        $this->model = new LogisticsRulesModel();
    }

    /**
     * @describe 获取列表
     * @author: Bobo
     * @date: 2024-06-05 18:02:26
     * @param [] type
     * @return Renderable
     */
    public function getList(array $where, int $page, int $limit)
    {
        if (0 >= $page || 100 < $limit) {
            return $this->error(100002);
        }

        $total = $this->model->where($where)->count();

        $list = $this->model
            ->where($where)
            ->with(['to_nation_name'])
            ->field([
                'id',
                'shipping_warehouse',
                'to_nation',
                'terms',
                'execution_date',
                'freight',
                'weight_lower',
                'notes',
                'surcharge_freight',
                'prescription',
                'status'
            ])
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()
            ->map(function ($item) {
                $item['to_nation_name'] = $item->to_nation_name->cname ? $item->to_nation_name->cname . '(' . $item->to_nation_name->full_name . ')' : null;
                return $item->toArray();
            })
            ->toArray();


        $data = ['list' => $list, 'total' => $total];
        return $this->success($data);
    }


    /**
     * 获取物流公司详情
     * @param int $id 物流公司ID
     */
    public function getOneById($id)
    {
        $logisticsRules = $this->model
            ->field([
                'id',
                'shipping_warehouse',
                'to_nation',
                'freight',
                'weight_lower',
                'terms',
                'surcharge_freight',
                'execution_date',
                'prescription',
                'status',
                'creator',
                'create_time',
                'updater',
                'update_time'
                // ... 其他需要的字段
            ])
            ->with([
                'shipping_warehouse_name' => function ($query) {
                    $query->field('id, name');
                },
                'to_nation_name' => function ($query) {
                    $query->field("id, concat (cname,' (',full_name,') ') as name");
                },
                'creator_name' => function ($query) {
                    $query->field('id, cname');
                },
                'updater_name' => function ($query) {
                    $query->field('id, cname');
                }
            ])
            ->append(['terms_value', 'status_value', 'prescription_value'])
            ->find($id);

        if (!$logisticsRules) {
            return $this->error(500001);
        }

        if ($logisticsRules) {
            $data = $logisticsRules->toArray();
            $data['to_nation_name'] = $data['to_nation_name']['name'] ?? null;
            $data['shipping_warehouse_name'] = $data['shipping_warehouse_name']['name'] ?? null;
            $data['creator_name'] = $data['creator_name']['cname'] ?? null;
            $data['updater_name'] = $data['updater_name']['cname'] ?? null;
            return $this->success($data);
        }

        return $this->success($logisticsRules->toArray());
    }

    /**
     * 创建物流公司
     * @param array $data 创建物流公司的数据
     */
    public function create($data)
    {

        try {
            // $data['product_id'] = 11;
            $res = $this->model->create($data);
            if ($res) {
                $this->logger->logOperation($res->id, 'LogisticsRules', '创建', '创建物流公司');
                return $this->success();
            } else {
                return $this->error(500001);
            }
        } catch (\Throwable $th) {
            return $this->error(500001, '服务器内部错误：' . $th->getMessage());
        }
    }

    /**
     * 更新物流公司
     * @param int $id 物流公司ID
     * @param array $data 更新物流公司的数据
     */
    public function update($data)
    {


        $res = $this->model->where('id', $data['id'])->find();
        if (!$res) {
            return $this->error(400000);
        }

        foreach ($data as $key => $value) {
            // if ('logistics_company' == $key) {
            //     $value = implode(',', $value);
            // }
            if ($res->$key !== $value) {
                $res->$key = $value;
            }
        }

        $result = $res->save();
        if ($result) {
            $this->logger->logOperation($res->id, 'LogisticsRules', '更新', '更新物流公司');
            return $this->success();
        } else {
            return $this->error(500001);
        }
    }

    /**
     * 删除物流公司
     * @param int $id 物流公司ID
     */
    public function delete($id)
    {

        $this->logger->logOperation($id, 'LogisticsRules', '删除', '删除物流公司');
        return $this->model->where('id', $id)->delete();
    }

    /**
     * @describe 批量逻辑删除物流公司
     * @author: Bobo
     * @date: 2024-06-26 14:53:00
     * @param [arr] @required $ids ID数组
     * @return Renderable
     */
    public function batchLogicalDelete($ids)
    {
        try {
            $this->model->whereIn('id', $ids)->update(['is_del' => time()]);
            $this->logger->logOperation(0, 'LogisticsRules', '批量删除', '批量删除物流规则id: ' . $ids);
            return $this->success();
        } catch (\Throwable $th) {
            return $this->error(500001, $th->getMessage());
        }
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2024-07-23 10:34:00
     * @param [type] @required
     * @return Renderable
     */
    public function getFieldEnum($field)
    {
        $res = $this->model->getFieldEnum($field);
        return [
            'code' => 0,
            'data' => $res
        ];
    }


    public function calculateFee($params)
    {
        if ($params['to_nation'] < 1 || isset($params['to_nation']) == false) {
            return $this->error(100200);
        }

        if ($params['terms'] < 1 || isset($params['terms']) == false) {
            return $this->error(100201);
        }

        if ($params['prescription'] < 1 || isset($params['prescription']) == false) {
            return $this->error(100202);
        }

        if (is_array($params['product']) == false || count($params['product']) < 1) {
            return $this->error(100203);
        }
        $product_list = [];
        $pids = array_column($params['product'], 'id');
        $productInfo = \app\admin\model\Product::where('id', 'in', $pids)->field('id,billing_weight,free_shipping,apply_rules')->select()->toArray();
        $productInfo = array_column($productInfo, null, 'id');
        foreach ($params['product'] as $k => $p) {
            $product_list[$k]['id'] = $p['id'];
            $product_list[$k]['wid'] = $p['wid'];
            $product_list[$k]['billing_weight'] = $productInfo[$p['id']]['billing_weight'] ?? '';
            $product_list[$k]['free_shipping'] = $productInfo[$p['id']]['free_shipping'] == 0 ? false : true;
            $product_list[$k]['apply_rules'] = $productInfo[$p['id']]['apply_rules']  == 0 ? false : true;
            $product_list[$k]['num'] = $p['quantity'];
        }
        $from_param['to_nation']  = $params['to_nation'];                 // 收货国家
        $from_param['terms']  = $params['terms'];
        $from_param['prescription']  = $params['prescription'];
        $from_param['product_list']  = $product_list;             // 商品信息
        return $this->getLogisticsFee($from_param);
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2024-08-20 13:22:41
     * @param [type] @required
     * @return Renderable
     */
    public function getLogisticsFee($params)
    {
        // 参数验证部分保持不变
        if ($params['to_nation'] < 1 || !isset($params['to_nation'])) {
            return $this->error(100200);
        }

        if ($params['terms'] < 1 || !isset($params['terms'])) {
            return $this->error(100201);
        }

        if ($params['prescription'] < 1 || !isset($params['prescription'])) {
            return $this->error(100202);
        }

        if (!is_array($params['product_list']) || count($params['product_list']) < 1) {
            return $this->error(100203);
        }

        if (!isset($params['currency'])) {
            $params['currency'] = 214;
        }

        foreach ($params['product_list'] as $value) {
            if (!isset($value['id']) || $value['id'] <= 0) {
                return $this->error(100204);
            }
            if (!isset($value['wid']) || $value['wid'] <= 0) {
                return $this->error(100205);
            }
            if (!isset($value['billing_weight']) || $value['billing_weight'] < 0) {
                return $this->error(100206);
            }
            if (!isset($value['num']) || $value['num'] <= 0) {
                return $this->error(100207);
            }
            if (!isset($value['free_shipping']) || !is_bool($value['free_shipping'])) {
                return $this->error(100208);
            }
            if (!isset($value['apply_rules']) || !is_bool($value['apply_rules'])) {
                return $this->error(100209);
            }
        }

        $all_wid = array_unique(array_column($params['product_list'], 'wid'));

        // +++ 扩展仓库ID集合：包含一级父仓库 +++ [修改点]
        $parentWids = [];
        foreach ($all_wid as $wid) {
            $parentId = $this->getParentWarehouse($wid);
            if ($parentId > 0) {
                $parentWids[] = $parentId;
            }
        }
        $all_wid = array_unique(array_merge($all_wid, $parentWids));
        // --- 扩展结束 ---

        $wid_count = $this->model
            ->name('warehouse')
            ->where('id', 'in', $all_wid)
            ->where('is_del', 0)
            ->where('status', 1)
            ->count();

        if ($wid_count != count($all_wid)) {
            return $this->error(100205);
        }

        // 构建IN占位符
        $inPlaceholders = implode(',', array_fill(0, count($all_wid), '?'));
        // 构建SQL查询
        $sql = "SELECT
            shipping_warehouse,
            to_nation,
            terms,
            prescription,
            freight,
            weight_lower,
            surcharge_freight,
            execution_date
        FROM (
            SELECT
                shipping_warehouse,
                to_nation,
                terms,
                prescription,
                freight,
                weight_lower,
                surcharge_freight,
                execution_date,
                ROW_NUMBER() OVER (
                    PARTITION BY shipping_warehouse, to_nation, terms, prescription
                    ORDER BY execution_date DESC, id DESC
                ) AS rn
            FROM db_logistics_rules
            WHERE shipping_warehouse IN ($inPlaceholders)
            AND execution_date <= ?
            AND to_nation = ?
            AND terms = ?
            AND prescription = ?
            AND is_del = 0
            AND status = 1
        ) t
        WHERE t.rn = 1";

        // 参数顺序：所有仓库ID + 目的国 + 条款 + 时效
        $bindParams = array_merge($all_wid, [
            date('Y-m-d H:i:s'),
            $params['to_nation'],
            $params['terms'],
            $params['prescription']
        ]);

        $all_logistics_rules = Db::query($sql, $bindParams);

        // 构建物流规则映射表
        $logisticsRuleMap = [];
        foreach ($all_logistics_rules as $rule) {
            $key = $rule['shipping_warehouse'] . '-' . $rule['to_nation'] . '-' . $rule['terms'] . '-' . $rule['prescription'];
            $logisticsRuleMap[$key] = $rule;
        }

        // 初始化总物流费用
        $logistics_fee = 0;

        // ========================== 核心修改开始 ==========================
        // 按仓库分组计算总计费重
        $warehouseTotals = [];
        foreach ($params['product_list'] as $product) {
            $wid = $product['wid'];
            if (!isset($warehouseTotals[$wid])) {
                $warehouseTotals[$wid] = [
                    'total_billing_weight' => 0,
                    'has_applied_rules' => false,
                    'matched' => false
                ];
            }

            $warehouseTotals[$wid]['total_billing_weight'] += $product['billing_weight'] * $product['num'];

            if ($product['free_shipping'] === false && $product['apply_rules'] === true) {
                $warehouseTotals[$wid]['has_applied_rules'] = true;
            }
        }

        // 计算仓库级物流费用
        $warehouseFees = [];
        $warehouseRules = [];

        foreach ($warehouseTotals as $wid => $totals) {
            // +++ 使用提取的方法查找规则 +++ [修改点]
            $ruleInfo = $this->findRuleWithParent($wid, $params, $logisticsRuleMap);
            $warehouseTotals[$wid]['matched'] = ($ruleInfo !== null);

            if ($totals['has_applied_rules'] && $ruleInfo !== null) {
                $rule = $ruleInfo['rule'];
                $usedWid = $ruleInfo['used_wid'];

                $effective_weight = max($totals['total_billing_weight'], $rule['weight_lower']);
                $warehouseFee = $effective_weight * $rule['freight'] + $rule['surcharge_freight'];

                $warehouseFees[$wid] = $warehouseFee;
                $warehouseRules[$wid] = $usedWid;
                $logistics_fee += $warehouseFee;
            }
        }

        // 重新遍历商品列表设置运费
        foreach ($params['product_list'] as &$product) {
            $wid = $product['wid'];

            $product['matched_rule'] = null;
            $product['original_wid'] = $wid;

            if ($product['free_shipping'] === false && $product['apply_rules'] === true) {
                if (isset($warehouseTotals[$wid]['matched']) && $warehouseTotals[$wid]['matched']) {
                    $product['matched_rule'] = true;
                    $product['matched_wid'] = $warehouseRules[$wid] ?? $wid;
                } else {
                    $product['matched_rule'] = false;
                }
                $product['logistics_fee'] = round($warehouseFees[$wid] ?? 0, 2);
            } else {
                $product['logistics_fee'] = 0;
            }
        }
        // ========================== 核心修改结束 ==========================

        if ($logistics_fee > 0 && $params['currency'] != 214) {
            $fetcher = new ExchangeRateHostAPI();
            $currencyData = Db::table('db_transaction_currency')->whereIn('id', '214,' . $params['currency'])->column('abbr', 'id');
            if (count($currencyData) < 2) {
                return $this->error(100700, '无效currency参数,获取汇率失败 ');
            }
            $exchange_rate = $fetcher->getRate($currencyData[214], $currencyData[$params['currency']]);
            $logistics_fee = round($logistics_fee * $exchange_rate, 2);
        }

        $data = [
            'logistics_fee' => $logistics_fee,
            'product_list' => $params['product_list']
        ];

        return $this->success($data);
    }

    // +++ 提取的规则查找方法 +++ [修改点]
    private function findRuleWithParent($wid, $params, &$logisticsRuleMap)
    {
        // 首次尝试使用当前仓库查找
        $key = $wid . '-' . $params['to_nation'] . '-' . $params['terms'] . '-' . $params['prescription'];

        if (isset($logisticsRuleMap[$key])) {
            return ['rule' => $logisticsRuleMap[$key], 'used_wid' => $wid];
        }

        // 尝试使用一级父仓库查找
        $parentWid = $this->getParentWarehouse($wid);
        if ($parentWid > 0) {
            $parentKey = $parentWid . '-' . $params['to_nation'] . '-' . $params['terms'] . '-' . $params['prescription'];
            if (isset($logisticsRuleMap[$parentKey])) {
                return ['rule' => $logisticsRuleMap[$parentKey], 'used_wid' => $parentWid];
            }
        }

        return null;
    }

    // 获取一级父仓库方法（保持不变）
    private function getParentWarehouse($wid)
    {
        $parent = $this->model
            ->name('warehouse')
            ->where('id', $wid)
            ->value('fl_warehouse_id');

        return $parent ? (int)$parent : 0;
    }






    /**
     * @describe 批量更新物流规则状态
     * @author: Bobo
     * @date: 2024-08-28 14:00:28
     * @param array $params
     * @return array
     */
    public function status($params)
    {
        if (empty($params['ids'])) {
            return ['code' => 1, 'message' => 'ID不能为空'];
        }

        $ids = explode(',', $params['ids']);

        try {
            $this->model->name('logistics_rules')
                ->where('id', 'in', $ids)
                ->where('is_del', 0)
                ->update([
                    'status' => $params['status'],
                    'updater' => $params['updater'],
                    'update_time' => date('Y-m-d H:i:s', $params['update_time'])
                ]);

            $this->logger->logOperation($ids, 'LogisticsRules', '修改', '批量修改状态');
            return $this->success();
        } catch (\Exception $e) {
            return $this->error(500001);
        }
    }

    /**
     *  物流规则 - 导出
     */
    public function export($where)
    {
        $arrData = ['code' => 0, 'message' => 'success'];

        /* 实例化Spreadsheet对象 */
        $spreadsheet = new Spreadsheet();
        /* 获取活动工作薄 */
        $sheet = $spreadsheet->getActiveSheet();

        // 字段
        $fields = ['shipping_warehouse', 'to_nation', 'terms', 'prescription', 'execution_date', 'freight', 'surcharge_freight', 'notes', 'weight_lower'];

        /* 定义一个excel的header表头 */
        $header = [

            'A1' => '发货仓库',
            'B1' => '目的国家',
            'C1' => '贸易条款',
            'D1' => '期望时效',
            'E1' => '执行时间',
            'F1' => '运费',
            'G1' => '附加费用',
            'H1' => '备注',
            'I1' => '最低计费重量'
        ];

        foreach ($header as $key => $value) {
            $sheet->setCellValue($key, $value);
        }

        $FieldEnum = $this->model->getFieldEnum('ALL');


        $terms = $FieldEnum['terms'];

        $prescription = $FieldEnum['prescription'];
        $warehouse = Db::name('warehouse')->column('id,name', 'id');

        /* 获取数据 */
        $data = $this->model->field($fields)->with([
            'to_nation_name' => function ($query) {
                $query->field("id,concat (cname,' (',full_name,') ') as name")->bind(['name' => 'to_nation']);
            }
        ])->where($where)
            ->select();
        if ($data) {
            $data = $data->toArray();
        } else {
            $data = [];
        }

        $list_data = [];
        foreach ($data as  $value) {
            $value['terms'] = $terms[$value['terms']];
            $value['prescription'] = $prescription[$value['prescription']];
            if (!empty($value['shipping_warehouse'])) {
                $value['shipping_warehouse'] = $warehouse[$value['shipping_warehouse']]['name'];
            }

            if (!empty($value['to_nation'])) {

                $to_nation_name = $value['to_nation_name']['name'] ?? null;
                // Ensure the value is a string, not an array
                $value['to_nation'] = is_array($to_nation_name) ? implode(' ', $to_nation_name) : (string)$to_nation_name;
                unset($value['to_nation_name']);
            }

            $list_data[] = $value;
        }

        $i = 2; //excel表格从第2行开始填入数据
        $columns = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
        foreach ($list_data as $k => $v) {
            $sheet->setCellValue($columns[0] . $i, $v[$fields[0]]);
            $sheet->setCellValue($columns[1] . $i, $v[$fields[1]]);
            $sheet->setCellValue($columns[2] . $i, $v[$fields[2]]);
            $sheet->setCellValue($columns[3] . $i, $v[$fields[3]]);
            $sheet->setCellValue($columns[4] . $i, $v[$fields[4]]);
            $sheet->setCellValue($columns[5] . $i, $v[$fields[5]]);
            $sheet->setCellValue($columns[6] . $i, $v[$fields[6]]);
            $sheet->setCellValue($columns[7] . $i, $v[$fields[7]]);
            $sheet->setCellValue($columns[8] . $i, $v[$fields[8]]);
            $i++; //$i从2累加
        }

        //定义文件名称，需要带有定义的后缀名
        $filename = date("Y-m-d_H_i_s") . '.xlsx';
        ob_end_clean(); //清除缓冲区,避免乱码
        //将输出重定向到客户端的web浏览器
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '";');
        header('Cache-Control: max-age=0');
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }





    /**
     *  物流规则 - 导入
     */
    public function import($params)
    {

        $fileInfo = $params['file'];
        if (empty($fileInfo)) {
            return $this->error(500001);
        }

        $filePath = $fileInfo->getPathName();

        $fileName = $fileInfo->getOriginalName();
        $fileNameExt = pathinfo($fileName, PATHINFO_EXTENSION); // 获取文件扩展名


        $reader = IOFactory::createReader('Xlsx');

        $spreadsheet = $reader->load($filePath);

        $worksheet = $spreadsheet->getActiveSheet();

        //总行数
        $row = $worksheet->getHighestRow();
        //总列数
        $column = $worksheet->getHighestColumn();

        $data = $temp = [];
        for ($rowIndex = 2; $rowIndex <= $row; $rowIndex++) {
            $temp['shipping_warehouse'] = $worksheet->getCell('A' . $rowIndex)->getValue();
            $temp['to_nation'] = $worksheet->getCell('B' . $rowIndex)->getValue();
            $temp['terms'] = $worksheet->getCell('C' . $rowIndex)->getValue();
            $temp['prescription'] = $worksheet->getCell('D' . $rowIndex)->getValue();
            $temp['execution_date'] = $worksheet->getCell('E' . $rowIndex)->getValue();
            if (is_numeric($worksheet->getCell('E' . $rowIndex)->getValue())) {
                // 将 Excel 日期序列号转换为 Unix 时间戳
                $temp['execution_date']  = Date::excelToDateTimeObject($worksheet->getCell('E' . $rowIndex)->getValue())->format('Y-m-d H:i:s');
            }
            $temp['freight'] = $worksheet->getCell('F' . $rowIndex)->getValue();
            $temp['surcharge_freight'] = $worksheet->getCell('G' . $rowIndex)->getValue();
            $temp['notes'] = $worksheet->getCell('H' . $rowIndex)->getValue();
            $temp['weight_lower'] = $worksheet->getCell('I' . $rowIndex)->getValue();
            $temp['row'] = $rowIndex;
            $data[] = $temp;
        }


        /* 检查枚举检查 */
        $FieldEnum = $this->model->getFieldEnum('ALL');
        $terms = $FieldEnum['terms'];
        $status = $FieldEnum['status'];
        $to_nation = $FieldEnum['to_nation'];

        //        $ccNameService = new \app\admin\service\RegionCountry();
        //        $to_nation = $ccNameService->selectOption()['list'];

        $warehouse = Db::name('warehouse')->column('id,name');
        $warehouse = array_column($warehouse, 'name', 'id');
        $prescription = $FieldEnum['prescription'];

        /* 检查枚举 */

        $info_data = [];

        foreach ($data as $key => $values) {

            /* 贸易条款 */
            if (empty(array_search($values['terms'], $terms))) {
                $info_data[] = [
                    'row' => $values['row'],
                    'info' => "[{$values['terms']}] " . '贸易条款错误'
                ];
                continue;
            }
            $values['terms'] = array_search($values['terms'], $terms);

            /* 发货仓库错误 */
            if (empty(in_array(trim($values['shipping_warehouse']), $warehouse))) {
                $info_data[] = [
                    'row' => $values['row'],
                    'info' => "[{$values['shipping_warehouse']}] " . '发货仓库错误'
                ];
                continue;
            }
            $values['shipping_warehouse'] = array_search($values['shipping_warehouse'], $warehouse);


            /* 期望时效 */
            if (empty(array_search($values['prescription'], $prescription))) {
                $info_data[] = [
                    'row' => $values['row'],
                    'info' => "[{$values['prescription']}] " . '期望时效错误'
                ];
                continue;
            }
            $values['prescription'] = array_search($values['prescription'], $prescription);

            /* 判断目的国家 */
            $countryItem = array_filter($to_nation, function ($item) use ($values) {
                return $item['label'] == $values['to_nation'];
            });

            if (!$countryItem) {
                $info_data[] = [
                    'row' => $values['row'],
                    'info' => "[{$values['to_nation']}] " . '目的国家错误'
                ];
                continue;
            }
            $countryItem = array_merge(...array_values($countryItem));

            $values['to_nation'] = $countryItem['value'];

            /* 运费 */
            if (empty($values['freight']) && $values['freight'] <= 0) {
                $info_data[] = [
                    'row' => $values['row'],
                    'info' => "[{$values['to_nation']}] " . '运费不能为空不能小于零'
                ];
                continue;
            }

            $isExist = $this->model
                ->where([
                    'shipping_warehouse' => $values['shipping_warehouse'],
                    'to_nation' => $values['to_nation'],
                    'terms' => $values['terms'],
                    'prescription' => $values['prescription'],
                    'execution_date' => $values['execution_date'],
                    'is_del' => 0
                ])
                ->find();
            //修改
            if ($isExist) {
                $updateResults = $this->model->where([
                    'id' => $isExist->id
                ])->update([
                    'freight' => $values['freight'],
                    'surcharge_freight' => $values['surcharge_freight'],
                    'notes' => $values['notes'],
                    'weight_lower' => $values['weight_lower'],
                    'update_time' => date('Y-m-d H:i:s', time())
                ]);
                if ($updateResults) {
                    $info_data[] = [
                        'row' => $values['row'],
                        'info' => '更新成功'
                    ];
                    continue;
                } else {
                    $info_data[] = [
                        'row' => $values['row'],
                        'info' => '修改失败'
                    ];
                    continue;
                }


                // 添加
            } else {
                $where['terms'] = $values['terms'];
                $where['prescription'] = $values['prescription'];
                $where['shipping_warehouse'] = $values['shipping_warehouse'];
                $where['to_nation'] = $values['to_nation'];
                $where['execution_date'] = $values['execution_date'];
                $result = $this->model->where($where)->find();
                if ($result) {
                    $info_data[] = [
                        'row' => $values['row'],
                        'info' => '已存在'
                    ];
                    continue;
                } else {
                    if ($this->model->create($values)) {
                        $info_data[] = [
                            'row' => $values['row'],
                            'info' => '创建成功'
                        ];
                    } else {
                        $info_data[] = [
                            'row' => $values['row'],
                            'info' => '写入失败'
                        ];
                    }
                }
            }
        }

        $res['code'] = 0;
        $res['data'] = $info_data;
        return $res;
    }

    /* 获取国家 Country Code */
    function getCountryCodeById($id, $countryData)
    {
        foreach ($countryData as $country) {
            if ($country['value'] == $id) {
                return $country['label'];
            }
        }
        return null;
    }

    /**
     * 获取物流费用
     * @param $param
     * @return array
     * @throws \Exception
     * 2024-12-30 17 02 40
     * author: jiang
     */
    public function getLogisticsFeeByWeb($param)
    {


        $ids = array_column($param['product_list'], 'id');

        $ProductshippingData = ProductModel::where('id', 'in', $ids)->field('free_shipping,apply_rules')->select();


        /*
        *（ free_shipping == 1  OR  apply_rules  == 0 ）
        * "是否包邮" 为是 或者 "是否应用我司物流规则"为否,则相应SKU商品的运费为0；其他则按照原有逻辑进行运费计算
        */

        if ($ProductshippingData) {
            $ProductshippingData = $ProductshippingData->toArray();
            $free_shipping_unique = array_unique(array_column($ProductshippingData, 'free_shipping'));
            $apply_rules_unique = array_unique(array_column($ProductshippingData, 'apply_rules'));

            /* 大于1 */
            $free_shippings = count($free_shipping_unique) > 1 ? 1 : $free_shipping_unique[0];
            $apply_rules = count($apply_rules_unique) > 1 ? 0 : $apply_rules_unique[0];

            if ($apply_rules == 1  or  $free_shippings  == 0) {
                return ['code' => 0, 'data' => '0.00'];
            }
        } else {
            throw new \Exception('未找到商品信息');
        }

        $LogisticsFee = $this->getLogisticsFee($param);
        if ($LogisticsFee['code'] != 0) {
            throw new \Exception('获取运费失败');
        }

        if ($LogisticsFee['data']['fee'] > 0 && $param['currency'] != 214) { // 运费大于0 并且 不是美元 转换
            $fetcher = new ExchangeRateHostAPI();
            $currencyData = Db::table('db_transaction_currency')->whereIn('id', '214,' . $param['currency'])->column('abbr', 'id');
            if (2 > count($currencyData)) {
                return $this->error(100700, '无效currency参数,获取汇率失败 ');
            }
            $exchange_rate = $fetcher->getRate($currencyData[214], $currencyData[$param['currency']]);
            $LogisticsFee['data']['fee'] = round($LogisticsFee['data']['fee'] * $exchange_rate, 2);
        }
        return [
            'code' => 0,
            'data' => $LogisticsFee['data']['fee']
        ];
    }
}
